package dcc.shannonfano;

import java.io.File;

public class SFTester {

	private static final String DIRECTORY_PATH = "testdata";
	private static final String ENCODER_EXT = ".sfe";
	private static final String DECODER_INFIX = "_decoded_.";

	public static void main(String[] args) {
		final File folder = new File(DIRECTORY_PATH);
		listFilesForFolder(folder);
	}

	private static void listFilesForFolder(final File folder) {
		for (final File fileEntry : folder.listFiles()) {
			if (fileEntry.isDirectory()) {
				listFilesForFolder(fileEntry);
			} else {
				encodeShannon(fileEntry.getAbsolutePath());
				// decodeShannon(fileEntry.getAbsolutePath());
			}
		}
	}

	private static void encodeShannon(String fileName) {

		if (fileName.endsWith(".sfe"))
			return;

		System.out.print("started reading: " + fileName);
		Encoder encode = new Encoder(fileName, fileName + ENCODER_EXT);
		try {
			encode.encodeFile();
		} catch (Exception e) {
			System.err.println("encode error: " + e.toString());
		}
		calculateCompressionRate(fileName, fileName + ENCODER_EXT);
	}

	private static void decodeShannon(String fileName) {

		if (!fileName.endsWith(".sfe"))
			return;

		System.out.println("started decoding: " + fileName);
		String[] outFile = fileName.split("\\.");
		Decoder decode = new Decoder(fileName, outFile[0] + DECODER_INFIX
				+ outFile[1]);
		try {
			decode.decodeFile();
		} catch (Exception e) {
			System.err.println("decode error: " + e.toString());
		}
	}

	private static void calculateCompressionRate(String input, String output) {

		File in = new File(input);
		File out = new File(output);
		long inSize = in.length();
		long outSize = out.length();
		double compressionRate = (double) (inSize - outSize) / (double) inSize;
		
		System.out.print(" - " + inSize / 1024);
		System.out.print(" (" + Math.round(compressionRate*1000.0)/1000.0);
		System.out.print(") - " + outSize / 1024);
		if (outSize < inSize) {
			System.out.print(" - true");
		}
		System.out.println();
	}
}